package com.bz.xtcx.manager.config;

import com.alibaba.fastjson.JSONObject;
import com.bz.xtcx.manager.entity.User;
import com.bz.xtcx.manager.vo.VoResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangkj
 *
 */
public class LoginFilter implements Filter{
    
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    private static final Logger logger = LoggerFactory.getLogger(LoginFilter.class);   
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.debug("过滤器初始化");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        VoResponse voRes = new VoResponse();
        voRes.setNull(voRes);
        voRes.setCode(401);
        voRes.setMessage("登录超时或在他处登录，请重新登录");
        HttpServletRequest req = (HttpServletRequest) request;
        req.setCharacterEncoding("UTF-8");
        HttpServletResponse res = (HttpServletResponse) response;
        res.setCharacterEncoding("UTF-8");
        String url = req.getRequestURI();
        String method = req.getMethod();
        logger.info(method + "-" + url);
        //System.out.println(method + "-" + url);
        String[] notFilterDirs = {"user/", "index/", "swagger", "v2/api-docs", "webjars/","cmsFloatBox/","lib/download"};
        for (int i = 0; i < notFilterDirs.length; i++) {
            String notFilterDirValue = notFilterDirs[i];
            if (url.indexOf(notFilterDirValue) != -1) {
                chain.doFilter(request, response);
                return;
            }
        }
        
        String token = req.getHeader("token");
        if(token == null) {
        	/*if(url.indexOf("upload") > 0 || url.indexOf("download") > 0 || url.indexOf("exportLib") > 0) {
        		token = String.valueOf(req.getParameter("token"));
        	}*/
        	token = String.valueOf(req.getParameter("token"));
        	if(token == null) {
        		res.setStatus(200);
                PrintWriter writer = response.getWriter();
                writer.write(JSONObject.toJSONString(voRes));
                return;
        	}
        }
        User user = null;
        Object obj = redisTemplate.opsForValue().get(token);
        if(obj == null){
            res.setStatus(200);
            PrintWriter writer = response.getWriter();
            writer.write(JSONObject.toJSONString(voRes));
            return;
        }
        user = (User) obj;
        redisTemplate.opsForValue().getOperations().expire(token, 60, TimeUnit.MINUTES);
        redisTemplate.opsForValue().getOperations().expire(user.getUserId(), 60, TimeUnit.MINUTES);
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        logger.debug("过滤器销毁");
    }

}
